package com.whmskj.xjlhsc.schedul;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.whmskj.xjlhbc.db.DataSourceType;
import com.whmskj.xjlhbc.db.DynamicDataSourceContextHolder;
import com.whmskj.xjlhsc.entity.DbStatistics;
import com.whmskj.xjlhsc.jitapi.mapper.InventoryMapper;
import com.whmskj.xjlhsc.mobie.empProPlan.entity.ProPersonnelStand;
import com.whmskj.xjlhsc.mobie.empProPlan.service.ProPersonnelStandService;
import com.whmskj.xjlhsc.schedul.async.mapper.PackageRecordMapper;
import com.whmskj.xjlhsc.schedul.async.po.PackageRecord;
import com.whmskj.xjlhsc.service.DbStatisticsService;
import com.whmskj.xjlhsc.utils.SCUtil;
import com.whmskj.xjlhsc.utils.SCUtil.ClassTimeRange;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: XJLHSC
 * @BelongsPackage: com.whmskj.xjlhsc.schedul
 * @Author: lk
 * @CreateTime: 2025-07-11
 * @Description: 统计员工班次打包数量
 * @Version: 1.0
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class PackagingStatisticsTask implements Task {

    private final PackageRecordMapper packagerecordMapper;
    private final static String S = "packagerecord2";
    private final static String N = "packagerecord";
    private final ProPersonnelStandService proPersonnelStandService;
    private final InventoryMapper inventoryMapper;
    private final DbStatisticsService dbStatisticsService;

    @Scheduled(cron = "0 29 9,21 * * ?")
    @Override
    public void taskGenerate() {
        ClassTimeRange classTimeRange = SCUtil.getClassDateTimeRange();
        String dateYmd = classTimeRange.getDateYmd();
        log.info("开始统计员工{}班次打包数量...", dateYmd);
//        classTimeRange.setDateYmd("2025-07-06");
//        classTimeRange.setStart(LocalDateTime.of(2025, 7, 6, 9, 30, 0));
//        classTimeRange.setEnd(LocalDateTime.of(2025, 7, 6, 21, 30, 0));
        List<DbStatistics> statisticsList = new ArrayList<>();
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SC.name());
        List<PackageRecord> packageRecordsS = packagerecordMapper.selectClassRangeRecord(classTimeRange, S);
        List<PackageRecord> packageRecordsN = packagerecordMapper.selectClassRangeRecord(classTimeRange, N);
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
        List<ProPersonnelStand> packegeEmp = proPersonnelStandService.getCurrentClassPackegeEmp(classTimeRange);
        String monthByYmd = inventoryMapper.getMonthByYmd(dateYmd);

        packegeEmp.parallelStream().forEach(stand -> {
            DbStatistics baseStat = createBaseStatistics(classTimeRange, stand, monthByYmd);

            if (ObjectUtil.equal(stand.getDeviceId(), 578)) {
                processAreaRecords(packageRecordsN, "北区", baseStat, statisticsList);
            } else {
                processAreaRecords(packageRecordsS, "南区", baseStat, statisticsList);
            }
        });

        if (!statisticsList.isEmpty()) {
            dbStatisticsService.saveBatch(statisticsList);
            log.info("成功保存{}条统计记录", statisticsList.size());
        }
    }

    private DbStatistics createBaseStatistics(ClassTimeRange range, ProPersonnelStand stand, String month) {
        DbStatistics stat = new DbStatistics();
        stat.setDateYmd(range.getDateYmd());
        stat.setClasss(range.getScclass().getDescription());
        stat.setTeamName(stand.getTeamName());
        stat.setEmpId(stand.getStaffId());
        stat.setEmpName(stand.getStaffName());
        stat.setPerformanceMonth(month);
        return stat;
    }

    private void processAreaRecords(List<PackageRecord> records, String area, DbStatistics baseStat, List<DbStatistics> resultList) {
        records.stream().collect(Collectors.groupingBy(PackageRecord::getVarietyNo)).forEach((varietyNo, recordList) -> {
            DbStatistics target = new DbStatistics();
            BeanUtil.copyProperties(baseStat, target);
            target.setArea(area);
            target.setVariety(varietyNo);
            target.setWeight(calculateTotalWeight(recordList));
            target.setBs(Double.parseDouble(String.valueOf(recordList.size())));
            resultList.add(target);
        });
    }

    private double calculateTotalWeight(List<PackageRecord> records) {
        return records.stream().mapToDouble(record -> record.getWeight().doubleValue()).sum();

    }

}
